﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace objass
{
    /// <summary>
    /// ClipBoardInput.xaml 的交互逻辑
    /// </summary>
    public partial class ClipBoardInput : Window
    {
        public string ClipboardText { get; set; }

        // 导入 Windows API 函数
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool AddClipboardFormatListener(IntPtr hwnd);

        private const uint WM_CLIPBOARDUPDATE = 0x031D;

        public ClipBoardInput()
        {
            InitializeComponent();
            Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            // 获取窗口句柄并注册剪贴板监听
            IntPtr hwnd = new WindowInteropHelper(this).Handle;
            HwndSource source = HwndSource.FromHwnd(hwnd);
            source.AddHook(WndProc);
            AddClipboardFormatListener(hwnd);
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_CLIPBOARDUPDATE)
            {
                // 剪贴板内容变化时触发
                if (Clipboard.ContainsText())
                {
                    string content = Clipboard.GetText();
                    //MessageBox.Show($"剪贴板已更新: {content}", "提示");
                    ClipboardText = content;

                    // 关闭对话框
                    DialogResult = true;
                    Window.GetWindow(this)?.Close();
                }
                handled = true;
            }
            return IntPtr.Zero;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
    }
}
